const path = require('path')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')

// 是否为生产环境
const isProduction = process.env.NODE_ENV === 'production'

// CDN 外部依赖配置（可选）
const cdn = {
  // 开发环境
  dev: {
    css: [],
    js: []
  },
  // 生产环境
  build: {
    css: [
      'https://unpkg.com/element-ui@2.11.0/lib/theme-chalk/index.css'
    ],
    js: [
      'https://unpkg.com/vue@2.6.10/dist/vue.min.js',
      'https://unpkg.com/vue-router@3.0.3/dist/vue-router.min.js',
      'https://unpkg.com/vuex@3.6.0/dist/vuex.min.js',
      'https://unpkg.com/axios@0.18.1/dist/axios.min.js',
      'https://unpkg.com/element-ui@2.11.0/lib/index.js'
    ]
  }
}

module.exports = {
  publicPath: process.env.VUE_APP_MENU_URL || '/',
  assetsDir: 'static',
  
  // 生产环境关闭 source map，减小打包体积
  productionSourceMap: !isProduction,
  
  // 开发服务器配置
  devServer: {
    open: true, // 自动打开浏览器
    host: '0.0.0.0',
    port: 8080,
    hotOnly: true, // 热更新
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/api': {
        target: process.env.VUE_APP_BASE_API,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  
  // 样式资源加载器配置
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [path.resolve(__dirname, './src/theme/style.less')]
    }
  },
  
  // Webpack 配置
  configureWebpack: config => {
    const plugins = []
    
    if (isProduction) {
      // Gzip 压缩
      plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path][base].gz',
          algorithm: 'gzip',
          test: /\.(js|css|html|svg)$/,
          threshold: 10240, // 只处理大于 10KB 的文件
          minRatio: 0.8,
          deleteOriginalAssets: false // 不删除源文件
        })
      )
      
      // 代码压缩优化
      config.optimization = {
        minimizer: [
          new TerserPlugin({
            terserOptions: {
              compress: {
                warnings: false,
                drop_console: true, // 删除 console
                drop_debugger: true, // 删除 debugger
                pure_funcs: ['console.log'] // 删除 console.log
              },
              output: {
                comments: false // 删除注释
              }
            },
            extractComments: false,
            parallel: true // 多线程并行处理
          })
        ],
        // 代码分割
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            // 第三方库
            libs: {
              name: 'chunk-libs',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial'
            },
            // Element UI 单独打包
            elementUI: {
              name: 'chunk-elementUI',
              priority: 20,
              test: /[\\/]node_modules[\\/]_?element-ui(.*)/
            },
            // 公共组件
            commons: {
              name: 'chunk-commons',
              test: path.resolve(__dirname, 'src/components'),
              minChunks: 3,
              priority: 5,
              reuseExistingChunk: true
            }
          }
        },
        // 运行时代码单独提取
        runtimeChunk: {
          name: 'runtime'
        }
      }
    }
    
    config.plugins = [...config.plugins, ...plugins]
    
    // 性能提示
    config.performance = {
      hints: isProduction ? 'warning' : false,
      maxEntrypointSize: 512000,
      maxAssetSize: 512000
    }
  },
  
  // Webpack 链式配置
  chainWebpack: config => {
    // 添加别名
    config.resolve.alias
      .set('@', path.resolve(__dirname, 'src'))
      .set('assets', path.resolve(__dirname, 'src/assets'))
      .set('components', path.resolve(__dirname, 'src/components'))
      .set('views', path.resolve(__dirname, 'src/view'))
    
    // 图片压缩
    config.module
      .rule('images')
      .use('url-loader')
      .loader('url-loader')
      .tap(options => Object.assign(options, { limit: 10240 })) // 小于 10KB 转 base64
    
    // SVG 优化
    config.module
      .rule('svg')
      .exclude.add(path.resolve(__dirname, 'src/assets/icons'))
      .end()
    
    // 预加载优化
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    
    // 预获取优化
    config.plugin('prefetch').tap(options => {
      options[0].fileBlacklist = options[0].fileBlacklist || []
      options[0].fileBlacklist.push(/\.map$/, /hot-update\.js$/)
      return options
    })
    
    // 生产环境优化
    if (isProduction) {
      // HTML 压缩
      config.plugin('html').tap(args => {
        args[0].minify = {
          removeComments: true,
          collapseWhitespace: true,
          removeAttributeQuotes: true,
          collapseBooleanAttributes: true,
          removeScriptTypeAttributes: true
        }
        // 注入 CDN（如果需要使用 CDN）
        // args[0].cdn = cdn.build
        return args
      })
      
      // 移除 console 和 debugger
      config.optimization.minimizer('terser').tap(args => {
        args[0].terserOptions.compress.drop_console = true
        args[0].terserOptions.compress.drop_debugger = true
        return args
      })
    }
    
    // 开发环境优化
    if (!isProduction) {
      // 开发环境注入 CDN
      config.plugin('html').tap(args => {
        args[0].cdn = cdn.dev
        return args
      })
    }
  },
  
  // CSS 相关配置
  css: {
    extract: isProduction, // 生产环境提取 CSS
    sourceMap: false, // 关闭 CSS source map
    loaderOptions: {
      less: {
        lessOptions: {
          javascriptEnabled: true
        }
      }
    }
  },
  
  // 文件缓存配置
  cache: {
    type: 'filesystem',
    cacheDirectory: path.resolve(__dirname, '.temp_cache')
  },
  
  // 并行处理
  parallel: require('os').cpus().length > 1
}